<template>
	<div class="w-full">
		<!-- PC 端刷新按钮 (一个简单的交互方案) -->
		<div class="hidden md:flex">
			<button
				@click="handleRefresh"
				:disabled="isLoading"
				title="刷新"
				class="fixed bottom-6 right-6 w-14 h-14 bg-blue-500 text-white rounded-full shadow-lg flex items-center justify-center hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition-all duration-300 disabled:bg-gray-400 disabled:cursor-not-allowed"
			>
				<!-- 
        SVG 刷新图标
        - 使用 :class 动态绑定 'animate-spin' 类
        - 当 isLoading 为 true 时，图标会旋转
      -->
				<svg
					:class="{ 'animate-spin': isLoading }"
					class="w-8 h-8"
					xmlns="http://www.w3.org/2000/svg"
					fill="none"
					viewBox="0 0 24 24"
					stroke-width="1.5"
					stroke="currentColor"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 11.664 0M2.985 19.644 6.166 16.46"
					/>
				</svg>
			</button>
		</div>

		<!-- 
      列表容器: 
      - 默认是单列 (space-y-6)
      - PC端 (md:) 变为多列网格 (grid)
    -->
		<div
			v-if="list.length > 0"
			class="p-4 md:p-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6"
		>
			<!-- 
        卡片:
        - 默认 (移动端): 使用 flex 布局 (图片在左，文字在右)
        - PC端 (md:): 恢复为 block 布局 (垂直堆叠)
      -->
			<div
				v-for="item in list"
				:key="item.id"
				class="bg-white dark:bg-gray-800 rounded-xl shadow-lg overflow-hidden transition-all duration-300 flex md:block"
			>
				<!-- 图片容器 -->
				<!-- 移动端: 固定宽度，高度自适应 -->
				<!-- PC端: 宽度100%，高度固定 -->
				<div class="flex-shrink-0 w-2/5 md:w-full">
					<img
						:src="item.photo"
						:alt="item.title"
						class="w-full h-full md:h-48 object-cover bg-gray-200 dark:bg-gray-700"
						:style="{
							aspectRatio: item.photoWidth / item.photoHeight,
						}"
					/>
				</div>

				<!-- 文字内容容器 -->
				<div class="flex flex-col justify-between p-4 flex-1">
					<div>
						<!-- 作者信息 -->
						<div class="flex items-center mb-2">
							<img
								:src="item.avatar"
								alt="author avatar"
								class="w-6 h-6 rounded-full mr-2"
							/>
							<span
								class="text-sm font-semibold text-gray-700 dark:text-gray-300 truncate"
								>{{ item.author }}</span
							>
						</div>
						<!-- 标题 -->
						<h3
							class="text-base font-bold text-gray-900 dark:text-white mb-2 line-clamp-2"
						>
							{{ item.title }}
						</h3>
					</div>

					<!-- 标签 -->
					<div v-if="item.tags && item.tags.length" class="mt-2">
						<div class="flex flex-wrap gap-1">
							<!-- 只显示前几个标签，防止溢出 -->
							<span
								v-for="tag in item.tags.slice(0, 3)"
								:key="tag"
								class="px-2 py-0.5 bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400 text-xs font-medium rounded-full"
							>
								#{{ tag }}
							</span>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 空状态 -->
		<div v-if="!isLoading && list.length === 0" class="text-center p-12">
			<p class="text-gray-500 dark:text-gray-400">
				该分类下暂无内容<br />
				当前选择的分类 ID: <strong>{{ categoryId || "未选择" }}</strong>
			</p>
		</div>

		<!-- 加载与结束状态指示器 -->
		<div class="text-center p-8 text-gray-500 dark:text-gray-400">
			<!-- 触发加载更多的哨兵元素 -->
			<div ref="sentinel"></div>

			<p v-if="isLoading">正在加载中...</p>
			<p v-if="isFinished">已经到底啦~</p>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from "vue";
import { usePexelsStore } from "@/store/modules/pexels";
import { storeToRefs } from "pinia";

const props = defineProps<{
	categoryId: string;
}>();

const pexelsStore = usePexelsStore();

// 使用 storeToRefs 来保持对 store state 和 getters 的响应式引用
const { list, isLoading, isFinished } = storeToRefs(pexelsStore);

// 用于 IntersectionObserver 的哨兵元素引用
const sentinel = ref<HTMLElement | null>(null);
let observer: IntersectionObserver | null = null;

// 监听分类ID变化，触发 store 的刷新 action
watch(
	() => props.categoryId,
	newId => {
		if (newId) {
			// 滚动到页面顶部，提供更好的用户体验
			// window.scrollTo(0, 0);
			// 调用 store action 来刷新列表
			pexelsStore.refreshList(newId);
		}
	},
	{ immediate: true }
); // immediate: true 保证组件初次加载时执行

// PC端刷新按钮的处理器
const handleRefresh = () => {
	if (props.categoryId) {
		pexelsStore.refreshList(props.categoryId);
	}
};

// 组件挂载后，设置 IntersectionObserver 来监听哨兵元素
onMounted(() => {
	const scrollRoot = document.querySelector("#home-scroll-container"); // 获取 Home.vue 中的滚动容器
	observer = new IntersectionObserver(
		([entry]) => {
			// 当哨兵元素进入视口时，加载更多数据
			if (entry && entry.isIntersecting) {
				pexelsStore.loadMore();
			}
		},
		{
			root: scrollRoot,
		}
	);

	if (sentinel.value) {
		observer.observe(sentinel.value);
	}
});

// 组件卸载前，清理 Observer
onUnmounted(() => {
	if (observer) {
		observer.disconnect();
	}
});
</script>
